package com.hugong.yxx.wksp.websocket;

import cn.hutool.core.thread.ThreadUtil;
import com.alibaba.fastjson.JSONObject;
import com.hugong.yxx.wksp.common.bean.WSMessage;
import com.hugong.yxx.wksp.persistence.entity.Message;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @description：
 * @author：LJ
 * @date: 2019/9/9 9:52
 * @modified By:
 */
@Component
@ServerEndpoint("/chat/{userID}")
public class RtcWebsocket {
    Logger log = LoggerFactory.getLogger(RtcWebsocket.class);
    /**
     * 在线数
     */
    private static int onlineCount = 0;
    /**
     * 客户端连接
     */
    private static Map<String, RtcWebsocket> clients = new ConcurrentHashMap<>();
    private Session session;
    private String userID;

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(@PathParam("userID") String userID, Session session) {
        //设置用户ID与WebSocket的对应关系
        this.userID = userID;
        this.session = session;
        addOnlineCount();
        clients.put(userID, this);
        log.info("已连接");
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        clients.remove(userID);
        subOnlineCount();
    }

    /**
     * 收到客户端消息后调用的方法
     */
    @OnMessage
    public void onMessage(String message) {
        log.info(message);
        WSMessage jsonTo = JSONObject.parseObject(message, WSMessage.class);
        sendMessageTo(jsonTo.getMessage(), jsonTo.getTo());
    }

    /**
     * 发生错误时调用
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.info("发生错误》》发生时间：" + System.currentTimeMillis() + "  ID是：" + session.getId());
        error.printStackTrace();
    }

    /**
     * 转发消息给 接收者
     *
     * @param message
     * @param to
     */
    public void sendMessageTo(String message, String to) {
        for (RtcWebsocket item : clients.values()) {
            if (item.userID.equals(to)) {
                try {
                    item.session.getAsyncRemote().sendText(message);
                } catch (Exception e) {
                    log.info("信息发送错误" + message);
                }
                //可以异步将消息写入数据库
                ThreadUtil.execAsync(() -> {
                    new Message(item.userID, to, message).insert();
                });
            }
        }
    }

    /**
     * 给所有WebSocket客户端发送消息
     *
     * @param message
     */
    public void sendMessageAll(String message) {
        for (RtcWebsocket item : clients.values()) {
            item.session.getAsyncRemote().sendText(message);
        }
    }

    /**
     * 已线程安全的方式获取在线人数
     *
     * @return
     */
    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    /**
     * 在线人数+1
     *
     * @return
     */
    public static synchronized void addOnlineCount() {
        RtcWebsocket.onlineCount++;
    }

    /**
     * 在线人数-1
     *
     * @return
     */
    public static synchronized void subOnlineCount() {
        RtcWebsocket.onlineCount--;
    }

    /**
     * 获取所有websocket链接
     *
     * @return
     */
    public static synchronized Map<String, RtcWebsocket> getClients() {
        return clients;
    }
}
